<script setup lang="ts">
import { ref } from "vue";
import { formRules } from "./utils/rule";
import { FormProps } from "./utils/types";
import UploadIcon from "@iconify-icons/ri/upload-2-line";
import { usePublicFormats } from "../formats";
import { message } from "@/utils/message";
import { baseUrlApi } from "../../api/utils";

const props = withDefaults(defineProps<FormProps>(), {
  id: String, // 添加 id prop
  formInline: () => ({
    park_name: "",
    car_number: "",
    images: "",
    question: ""
  })
});

const ruleFormRef = ref();
const newFormInline = ref(props.formInline);

function getRef() {
  return ruleFormRef.value;
}

const { parkListOptions } = usePublicFormats();

/** 上传文件前校验 */
const onBefore = file => {
  if (!["image/jpeg", "image/png", "image/gif"].includes(file.type)) {
    message("只能上传图片");
    return false;
  }
  const isExceed = file.size / 1024 / 1024 > 5;
  if (isExceed) {
    message(`单个图片大小不能超过5MB`);
    return false;
  }
};

const successUpload = response => {
  newFormInline.value.images.pop();
  newFormInline.value.images.push({
    name: response.data.url
  });
};

const uploadUrl = baseUrlApi("upload");

defineExpose({ getRef });
</script>

<template>
  <el-form
    ref="ruleFormRef"
    :model="newFormInline"
    :rules="formRules"
    label-width="82px"
  >
    <el-form-item label="停车场" prop="park_name">
      <el-select
        v-model="newFormInline.park_name"
        placeholder="请选择停车场"
        class="w-full"
        clearable
      >
        <el-option
          v-for="item in parkListOptions"
          :key="item.label"
          :label="item.label"
          :value="item.label"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="车牌号" prop="car_number">
      <el-input
        v-model="newFormInline.car_number"
        clearable
        placeholder="请输入车牌号"
      />
    </el-form-item>
    <el-form-item label="图片" prop="image">
      <el-upload
        ref="uploadRef"
        v-model:file-list="newFormInline.images"
        :action="uploadUrl"
        drag
        multiple
        :limit="5"
        class="!w-[200px]"
        :before-upload="onBefore"
        :on-success="successUpload"
      >
        <div class="el-upload__text">
          <IconifyIconOffline
            :icon="UploadIcon"
            width="26"
            class="m-auto mb-2"
          />
          可点击或拖拽上传
        </div>
      </el-upload>
    </el-form-item>
    <el-form-item label="问题描述" prop="question">
      <el-input
        v-model="newFormInline.question"
        placeholder="请输入问题描述"
        type="textarea"
      />
    </el-form-item>
  </el-form>
</template>
